package vip.aster.system.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import vip.aster.common.utils.AddressUtils;
import vip.aster.common.utils.HttpContextUtils;
import vip.aster.common.utils.IpUtils;
import vip.aster.common.utils.PageInfo;
import vip.aster.common.utils.ExcelUtils;
import vip.aster.framework.i18n.MessageUtils;
import vip.aster.system.entity.SysLogLogin;
import vip.aster.system.mapper.SysLogLoginMapper;
import vip.aster.system.query.SysLogLoginQuery;
import vip.aster.system.service.SysLogLoginService;
import vip.aster.system.vo.SysLogLoginVO;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 访问日志 服务实现类
 * </p>
 *
 * @author Aster
 * @since 2023-11-28 10:36
 */
@Service
@AllArgsConstructor
public class SysLogLoginServiceImpl extends ServiceImpl<SysLogLoginMapper, SysLogLogin> implements SysLogLoginService {
    private SysLogLoginMapper sysLogLoginMapper;

    @Override
    public void save(String userId, String username, String status, String operation, String tenantId) {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        assert request != null;
        String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
        String ip = IpUtils.getIpAddr(request);
        String address = AddressUtils.getRealAddressByIp(ip);

        SysLogLogin sysLogLogin = new SysLogLogin();
        sysLogLogin.setUsername(username);
        sysLogLogin.setIpAddress(ip);
        sysLogLogin.setLoginLocation(address);
        sysLogLogin.setUserAgent(userAgent);
        sysLogLogin.setStatus(status);
        sysLogLogin.setOperation(operation);
        sysLogLogin.setLoginTime(LocalDateTime.now());
        sysLogLogin.setUserId(userId);
        sysLogLogin.setTenantId(tenantId);

        sysLogLoginMapper.insert(sysLogLogin);
    }

    @Override
    public PageInfo<SysLogLoginVO> pageList(SysLogLoginQuery query) {
        Page<SysLogLogin> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<SysLogLogin> pageList = sysLogLoginMapper.selectPage(page, getWrapper(query));
        return new PageInfo<>(SysLogLoginVO.convertList(pageList.getRecords()), pageList.getTotal());
    }

    @Override
    public void export(SysLogLoginQuery query) {
        List<SysLogLogin> list = this.list(getWrapper(query));
        List<SysLogLoginVO> loginList = SysLogLoginVO.convertList(list);
        // 写到浏览器打开
        String excelName = "login_log_" + LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.NORM_DATE_PATTERN);
        String sheetName = MessageUtils.message("log.login.sheetName");
        ExcelUtils.excelExport(SysLogLoginVO.class, excelName, sheetName, loginList);
    }

    private LambdaQueryWrapper<SysLogLogin> getWrapper(SysLogLoginQuery query) {
        LambdaQueryWrapper<SysLogLogin> wrapper = Wrappers.lambdaQuery();

        wrapper.like(StrUtil.isNotBlank(query.getUsername()), SysLogLogin::getUsername, query.getUsername());
        wrapper.eq(StrUtil.isNotBlank(query.getStatus()), SysLogLogin::getStatus, query.getStatus());
        if (StrUtil.isNotBlank(query.getStartTime())) {
            wrapper.ge(SysLogLogin::getLoginTime, LocalDateTimeUtil.parse(query.getStartTime(), DatePattern.NORM_DATETIME_PATTERN));
        }
        if (StrUtil.isNotBlank(query.getEndTime())) {
            wrapper.le(SysLogLogin::getLoginTime, LocalDateTimeUtil.parse(query.getEndTime(), DatePattern.NORM_DATETIME_PATTERN));
        }
        wrapper.orderByDesc(SysLogLogin::getLoginTime);
        return wrapper;
    }
}
